from PySide2.QtCore import Qt
from PySide2.QtCore import QPointF, QRect, QPoint, QSize
from PySide2.QtWidgets import QSizePolicy
from PySide2.QtWidgets import QLayout
from PySide2.QtWidgets import QStyle

class FlowLayout(QLayout):
    def __init__(self, **kwargs):
        if 'parent' in kwargs:
            parent = kwargs['parent']
        else:
            parent = None
        if 'margin' in kwargs:
            self.m_margin = kwargs['margin']
        else:
            self.m_margin = 0
        if 'hSpacing' in kwargs:
            self.m_hSpace = kwargs['hSpacing']
        else:
            self.m_hSpace = 0
        if 'vSpacing' in kwargs:
            self.m_vSpace = kwargs['vSpacing']
        else:
            self.m_vSpace = 0
        self.itemList = []
        super(FlowLayout, self).__init__(parent)

        self.setContentsMargins(self.m_margin, self.m_margin, self.m_margin, self.m_margin)

    def __del__(self):
        while True:
            item = self.takeAt(0)
            if (item):
                del item
            else:
                break

    def addItem(self, item):
        self.itemList.append(item)

    def horizontalSpacing(self):
      if (self.m_hSpace >= 0):
          return self.m_hSpace
      else:
          return self.smartSpacing(QStyle.PM_LayoutHorizontalSpacing)

    def verticalSpacing(self):
      if (self.m_vSpace >= 0):
          return self.m_vSpace
      else:
          return self.smartSpacing(QStyle.PM_LayoutVerticalSpacing)

    def count(self):
        return len(self.itemList)

    def itemAt(self, index):
        # print (self.itemList)
        # print (index)
        if index>=len(self.itemList):
            return None
        return self.itemList[index]

    def takeAt(self, index):
      if (index >= 0 and index < len(self.itemList)):
          return self.itemList.pop(index)
      else:
          return 0

    def expandingDirections(self):
        return Qt.Horizontal

    def hasHeightForWidth(self):
        return True
    
    def heightForWidth(self, width):
        height = self.doLayout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()
        for item in self.itemList:
            size = size.expandedTo(item.minimumSize())
        size += QSize(2*self.margin(), 2*self.margin())
        return size

    def doLayout(self, rect, testOnly):
        cmar = self.contentsMargins()
        effectiveRect = rect.adjusted(+cmar.left(), +cmar.top(), -cmar.right(), -cmar.bottom())
        x = effectiveRect.x()
        y = effectiveRect.y()
        lineHeight = 0

        for item in self.itemList:
            wid = item.widget()
            spaceX = self.horizontalSpacing()
            if (spaceX == -1):
                spaceX = wid.style().layoutSpacing(
                    QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
            spaceY = self.verticalSpacing()
            if (spaceY == -1):
                spaceY = wid.style().layoutSpacing(
                    QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
            nextX = x + item.sizeHint().width() + spaceX
            if (nextX - spaceX > effectiveRect.right() and lineHeight > 0):
                x = effectiveRect.x()
                y = y + lineHeight + spaceY
                nextX = x + item.sizeHint().width() + spaceX
                lineHeight = 0

            if (not testOnly):
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = nextX
            lineHeight = max(lineHeight, item.sizeHint().height())

        return y + lineHeight - rect.y() + cmar.bottom()

    def smartSpacing(self, pm):
        parent = self.parent()
        if (not parent):
            return -1
        elif (parent.isWidgetType()):
            return parent.style().pixelMetric(pm, 0, parent)
        else:
            return parent.spacing()